<template>
  <div class="dashboard-editor-container">
    <div class="head_color">
      <div class="head_center">
        <div class="head_title" style="float: left;cursor: pointer;" @click="toFYLZ">
          {{sysName}}
        </div>
        <div style="float: right;">
          <el-menu :default-active="activeIndex"
                   router
                   class="el-menu-demo" mode="horizontal"
                   background-color="#006BB7"
                   text-color="#EAF2ED"
                   active-text-color="#ffd04b">
            <el-menu-item index="/planeFace">平面图</el-menu-item>
            <el-menu-item index="/monitorVideo">监控一览</el-menu-item>
            <el-menu-item index="/monitorVideoGz">关注监控</el-menu-item>
            <el-menu-item index="/frontEndIndex">设备列表</el-menu-item>
            <el-menu-item @click="toGFBC">共富班车</el-menu-item>
            <el-menu-item index="/relFace">发布界面</el-menu-item>
            <el-menu-item index="/index">后台管理</el-menu-item>
            <el-menu-item >
              <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
                <div style="color: #EAF2ED;">
                  系统管理员
                  <i class="el-icon-caret-bottom" style="color: #EAF2ED;" />
                </div>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item divided >
                    <span><a href="WebComponentsKit.exe" target="_blank" download="WebComponentsKit.exe">视频组件</a></span>
                  </el-dropdown-item>
                  <el-dropdown-item divided @click.native="logout">
                    <span>退出登录</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-menu-item>

          </el-menu>
        </div>
      </div>
    </div>

    <div style="width: 1170px;margin-left: auto;margin-right: auto;">
      <div style="margin-top: 10px;">
        <el-row>
          <el-col :span="6">
            <el-card class="box-card">
              <el-switch
                v-model="netWork"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="外网"
                inactive-text="内网">
              </el-switch>
            </el-card>
            <el-card class="box-card" v-if="isYtFlag" style="text-align: center;">
                <div>
                  <div class="el-button-group ">
                    <div class="el-button primary" @mousedown="mouseDownPTZControl(5)" @mouseup="mouseUpPTZControl">左上</div>
                    <div class="el-button primary" @mousedown="mouseDownPTZControl(1)" @mouseup="mouseUpPTZControl">向上</div>
                    <div class="el-button primary" @mousedown="mouseDownPTZControl(7)" @mouseup="mouseUpPTZControl">右上</div>
                  </div>
                  <br/>
                  <div class="el-button-group ">
                    <div class="el-button primary" @mousedown="mouseDownPTZControl(3)" @mouseup="mouseUpPTZControl">向左</div>
                    <div class="el-button primary" @mousedown="mouseDownPTZControl(9)" @mouseup="mouseUpPTZControl">自动</div>
                    <div class="el-button primary" @mousedown="mouseDownPTZControl(4)" @mouseup="mouseUpPTZControl">向右</div>
                  </div>
                  <br/>
                  <div class="el-button-group ">
                    <div class="el-button primary" @mousedown="mouseDownPTZControl(6)" @mouseup="mouseUpPTZControl">左下</div>
                    <div class="el-button primary" @mousedown="mouseDownPTZControl(2)" @mouseup="mouseUpPTZControl">向下</div>
                    <div class="el-button primary" @mousedown="mouseDownPTZControl(8)" @mouseup="mouseUpPTZControl">右下</div>
                  </div>
                </div>
            </el-card>
            <el-card class="box-card" v-else style="text-align: center;pointer-events: none;background-color: #ccc;filter:alpha(Opacity=50);-moz-opacity:0.5;opacity: 0.5;">
              <div>
                <div class="el-button-group ">
                  <div class="el-button primary" @mousedown="mouseDownPTZControl(5)" @mouseup="mouseUpPTZControl">左上</div>
                  <div class="el-button primary" @mousedown="mouseDownPTZControl(1)" @mouseup="mouseUpPTZControl">向上</div>
                  <div class="el-button primary" @mousedown="mouseDownPTZControl(7)" @mouseup="mouseUpPTZControl">右上</div>
                </div>
                <br/>
                <div class="el-button-group ">
                  <div class="el-button primary" @mousedown="mouseDownPTZControl(3)" @mouseup="mouseUpPTZControl">向左</div>
                  <div class="el-button primary" @mousedown="mouseDownPTZControl(9)" @mouseup="mouseUpPTZControl">自动</div>
                  <div class="el-button primary" @mousedown="mouseDownPTZControl(4)" @mouseup="mouseUpPTZControl">向右</div>
                </div>
                <br/>
                <div class="el-button-group ">
                  <div class="el-button primary" @mousedown="mouseDownPTZControl(6)" @mouseup="mouseUpPTZControl">左下</div>
                  <div class="el-button primary" @mousedown="mouseDownPTZControl(2)" @mouseup="mouseUpPTZControl">向下</div>
                  <div class="el-button primary" @mousedown="mouseDownPTZControl(8)" @mouseup="mouseUpPTZControl">右下</div>
                </div>
              </div>
            </el-card>
            <el-card class="box-card" :style="{height:tabHt+'px'}">
              <div :style="{height:(tabHt-20)+'px'}" >
                <el-scrollbar style="height: 100%;">
                  <div v-for="videoInfo in videoInfoList" style="cursor: pointer;"
                       :class="{active: videoInfo.id==videoId}" @click="clkVideoInfo(videoInfo)" class="text item">
                    <span style="font-size: 1.2em;line-height: 2;">{{videoInfo.name }}</span>
                  </div>
                </el-scrollbar>
              </div>
            </el-card>
          </el-col>
          <el-col :span="18">
            <el-row>
              <div id="divPlugin" class="plugin" style="margin-left: 20px;"></div>
            </el-row>
            <el-row hidden>
              <el-form :inline="true" :model="hkvInfo" class="demo-form-inline">
                <el-row style="margin-top: 10px;">
                  <el-form-item label="ip地址">
                    <el-input v-model="hkvInfo.ip" placeholder="ip" style="width: 150px;" readonly></el-input>
                  </el-form-item>
                  <el-form-item label="端口">
                    <el-input v-model="hkvInfo.port" placeholder="port" style="width: 150px;" readonly></el-input>
                  </el-form-item>
                  <el-form-item label="用户名">
                    <el-input v-model="hkvInfo.username" placeholder="username" style="width: 150px;" readonly></el-input>
                  </el-form-item>
                  <el-form-item label="密码">
                    <el-input v-model="hkvInfo.password" placeholder="password" style="width: 150px;" readonly></el-input>
                  </el-form-item>
                </el-row>
                <el-row style="margin-top: 10px;">
                  <el-col>
                    <el-form-item>
                      <el-button type="primary" :loading="loginLoading" @click="onLogin">登录</el-button>
                      <el-button type="primary" :loading="startPlayLoading" @click="clickStartRealPlay">开始预览</el-button>
                      <el-button type="primary" @click="clickStopRealPlay">停止预览</el-button>
                      <el-button type="primary" @click="onLogout">退出</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-row>
            <el-row hidden>
              <div>
                <label>数字通道列表: </label>
                <el-tag type="success" class="my-tag" v-for="(item,index) in hkvInfo.channels" :key="index">{{item}}</el-tag>
              </div>
            </el-row>
          </el-col>
        </el-row>
      </div>

    </div>

  </div>
</template>

<script>
  const defaultSettings = require('@/settings.js');
  import { listVideoInfo } from "@/api/basic/videoInfo";
  import {WebVideoCtrl} from '@/assets/js/webVideoCtrl.js'

export default {
  name: "MonitorVideo",
  components: {
  },
  data() {
    return {
      sysName: defaultSettings.title,
      activeIndex: '/monitorVideo',
      videoId:undefined,
      // 视频配置表格数据
      videoInfoList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100
      },
      netWork:true,
      // <!-- 视频监控
      hkvInfo: {
        ip: '',//海康威视摄像头/硬盘录像机的ip地址
        port: '',//海康威视摄像头/硬盘录像机的端口
        username: '',//海康威视摄像头/硬盘录像机的用户名
        password: '',//海康威视摄像头/硬盘录像机的密码
        channels: [],//海康威视摄像头/硬盘录像机的通道
      },
      hkvInfoOld: {//退出登入参数
        ip: '',//海康威视摄像头/硬盘录像机的ip地址
        port: '',//海康威视摄像头/硬盘录像机的端口
      },
      mySelectWnd: 0,//当前选中的窗口
      g_bPTZAuto: false,
      iProtocol: 1,
      loginLoading: false,
      startPlayLoading: false,
      iStreamType: 1,
      bZeroChannel: false,
      iRtspPort: 0,
      flag:true,
      isYtFlag:false
      // 视频监控 -->
    };
  },
  created() {
    this.getList();
  },
  mounted: function () {
    this.videoInitPlugin(); // 初始化video界面
  },
  destroyed: function () {
    this.clickStopRealPlay();
    this.onLogout();
  },
  computed: {
    tabHt(){
      return this.$store.state.app.tableHeight.ht - 110
    }
  },
  methods: {
    toFYLZ(){
      window.open('https://fylz.zjagri.cn/ppthtml/index.html','_blank')
    },
    toGFBC(){
      window.open('https://www.danss.work/lszx/','_blank')
    },
    async logout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('LogOut').then(() => {
          location.href = '/index';
        })
      })
    },
    /** 查询视频配置列表 */
    getList() {
      this.flag = true;
      this.videoInfoList = [];
      listVideoInfo(this.queryParams).then(response => {
        this.videoInfoList = response.rows;
        if(this.videoInfoList.length>0){
          this.$nextTick(()=>{
            this.clkVideoInfo(this.videoInfoList[0])
          })
        }
      });
    },
    clkVideoInfo(videoInfo){
      // console.log('切换登录------------')
      if(videoInfo.id == this.videoId){
        return false;
      }
      if(videoInfo.isYt == 'Y'){
        this.isYtFlag = true;
      }else{
        this.isYtFlag = false;
      }
      if(this.netWork){
        this.hkvInfo.ip = videoInfo.ipCode;
        this.hkvInfo.port = videoInfo.portCode;
      }else{
        this.hkvInfo.ip = videoInfo.insideIp;
        this.hkvInfo.port = videoInfo.insidePort;
      }
      this.hkvInfo.username = videoInfo.account;
      this.hkvInfo.password = videoInfo.password;
      this.hkvInfo.channels = [];
      this.videoId = videoInfo.id;
      if(!this.flag){
        // console.log('切换登录A------------')
        this.onLogoutAndLogin();
      }else{
        // console.log('切换登录B------------')
        this.onLogin();
      }
      // if(this.flag){
      //   this.flag = false;
      // }
    },
    // <!-- 视频监控
    onLogin() {
      try {
        let that = this;
        that.loginLoading = true;
        // console.log('开始登录设备')
        // 登录设备
        WebVideoCtrl.I_Login(that.hkvInfo.ip, that.iProtocol, that.hkvInfo.port, that.hkvInfo.username, that.hkvInfo.password, {
          async: true,
          success: function (xmlDoc) {
            // console.log('xmlDoc2', xmlDoc);//不能删除
            //TODO 获取通道信息
            setTimeout(function () {
              that.getChannelInfo();
              that.getDevicePort(that.hkvInfo.ip + "_" + that.hkvInfo.port);
            }, 10);
            setTimeout(function() {
              that.hkvInfoOld.ip = that.hkvInfo.ip;
              that.hkvInfoOld.port = that.hkvInfo.port;
              that.clickStartRealPlay();
            }, 500)
            that.loginLoading = false;
            that.flag = false;
            // that.$message({
            //   showClose: true,
            //   message: '登录成功',
            //   type: 'success'
            // });
          },
          error: function () {
            that.loginLoading = false;
            // console.log('登录失败')
          }
        });
      }catch(err){
        // console.log(err)
      }
    },
    onLogoutAndLogin() {
      try {
        if(this.hkvInfoOld.ip != '' && this.hkvInfoOld.port!=''){
          // this.hkvInfo.channels = [];
          let szDeviceIdentify = this.hkvInfoOld.ip + "_" + this.hkvInfoOld.port;
          let iRet = WebVideoCtrl.I_Logout(szDeviceIdentify);
          if (0 == iRet) {
            // this.$message({
            //   showClose: true,
            //   message: '退出成功',
            //   type: 'success'
            // });
            this.hkvInfoOld.ip = '';
            this.hkvInfoOld.port = '';
            this.onLogin();
            return true;
          } else {
            // this.$message({
            //   showClose: true,
            //   message: '退出失败',
            //   type: 'error'
            // });
            return false;
          }
        }else{
          this.hkvInfoOld.ip = '';
          this.hkvInfoOld.port = '';
          this.onLogin();
          return true;
        }
      }catch(err){
        //console.log('错误！')
      }
    },
    onLogout() {
      if(this.hkvInfoOld.ip != '' && this.hkvInfoOld.port!=''){
        this.hkvInfo.channels = [];
        let szDeviceIdentify = this.hkvInfoOld.ip + "_" + this.hkvInfoOld.port;
        let iRet = WebVideoCtrl.I_Logout(szDeviceIdentify);
        if (0 == iRet) {
          // this.$message({
          //   showClose: true,
          //   message: '退出成功',
          //   type: 'success'
          // });
          this.hkvInfoOld.ip = '';
          this.hkvInfoOld.port = '';
          return true;
        } else {
          // this.$message({
          //   showClose: true,
          //   message: '退出失败',
          //   type: 'error'
          // });
          return false;
        }
      }
    },
    clickStartRealPlay() {
      this.clickStopRealPlay();
      // 开始预览
      let that = this;
      that.startPlayLoading = true;
      let szDeviceIdentify = that.hkvInfo.ip + "_" + that.hkvInfo.port;

      let j = that.hkvInfo.channels.length > 4 ? 4 : that.hkvInfo.channels.length;
      for (let i = 0; i < j; i++) {
        setTimeout(that.startRealPlay(szDeviceIdentify, i, that.hkvInfo.channels[i]), 500);
      }
      that.startPlayLoading = false;
    },
    videoInitPlugin: function () {
      let iRet = WebVideoCtrl.I_CheckPluginInstall();
      if (iRet === -1) {
        alert('您还未安装过插件，双击开发包目录里的WebComponentsKit.exe安装');
        return;
      }
      this.initPlugin()
    },
    initPlugin: function () {
      let that = this;

      WebVideoCtrl.I_InitPlugin(800, 600, {
        bWndFull: true,//是否支持单窗口双击全屏，默I_CheckPluginInstall
        iWndowType: 2,
        myCbSelWnd: function (xmlStr) { //自己新增的方法
          let jsonObj = that.$x2js.xml2js(xmlStr);
          that.mySelectWnd = jsonObj.RealPlayInfo.SelectWnd;
          let szInfo = "当前选择的窗口编号：" + that.mySelectWnd;
          // console.log(szInfo);
        },
        cbInitPluginComplete: function () {
          WebVideoCtrl.I_InsertOBJECTPlugin("divPlugin");
          //设置窗口1X1
          WebVideoCtrl.I_ChangeWndNum(1);
          // 检查插件是否最新
          if (WebVideoCtrl.I_CheckPluginVersion() === -1) {
            alert("检测到新的插件版本，双击开发包目录里的WebComponentsKit.exe升级！");
            return;
          }
        }
      });
    },
    getDevicePort: function (szDeviceIdentify) {
      let oPort = WebVideoCtrl.I_GetDevicePort(szDeviceIdentify);
      this.iRtspPort = oPort.iRtspPort;
    },
    startRealPlay: function (szDeviceIdentify, iWndIndex, iChannelID) {
      let that = this;
      WebVideoCtrl.I_StartRealPlay(szDeviceIdentify, {
        iRtspPort: that.iRtspPort,
        iWndIndex: iWndIndex,
        iStreamType: 1,
        iChannelID: iChannelID,
        bZeroChannel: that.bZeroChannel,
        success: function () {
          // that.$notify({
          //   title: '成功',
          //   message: '开始预览通道' + iChannelID + '成功',
          //   type: 'success'
          // });
        },
        error: function (status, xmlDoc2) {
          // console.log(xmlDoc2)//不能删除
          // that.$notify({
          //   title: '失败',
          //   message: '开始预览通道' + iChannelID + '失败',
          //   type: 'error'
          // });
          if (status === 403) {
            // console.log("szInfo 设备不支持Websocket取流！");
          } else {
            // console.log("开始预览失败 ", status, xmlDoc2);
          }
        }
      });
    },
    clickStopRealPlay: function () {
      let j = this.hkvInfo.channels.length > 4 ? 4 : this.hkvInfo.channels.length;
      for (let i = 0; i < j; i++) {
        setTimeout(this.stopRealPlay(i), 1000);
      }
    },
    stopRealPlay: function (iWndIndex) {
      let that = this;
      WebVideoCtrl.I_Stop({
        iWndIndex: iWndIndex,
        success: function () {
          // that.$notify({
          //   title: '成功',
          //   message: '停止预览窗口' + iWndIndex + '成功',
          //   type: 'success'
          // });
        },
        error: function () {
          // that.$notify({
          //   title: '失败',
          //   message: '停止预览窗口' + iWndIndex + '失败',
          //   type: 'error'
          // });
        }
      });
    },
    // 获取通道，实际上可以根据自己的项目，获取数字通道，模拟通道，零通道中的一个或多个，不用全部获取（提高效率）
    getChannelInfo: function () {
      let that = this;
      let szDeviceIdentify = this.hkvInfo.ip + "_" + this.hkvInfo.port;
      // debugger
      // 数字通道
      that.hkvInfo.channels = [];
      WebVideoCtrl.I_GetDigitalChannelInfo(szDeviceIdentify, {
          async: false,
          mysuccess: function (xmlStr) {
            // console.log('mysuccess I_GetDigitalChannelInfo: ', xmlStr)
            let jsonObj = that.$x2js.xml2js(xmlStr)
            let list = jsonObj.InputProxyChannelStatusList.InputProxyChannelStatus;
            for (let x = 0; x < list.length; x++) {
              that.hkvInfo.channels.push(list[x].id);
            }
          },
          success: function (xmlDoc) {
          },
          error: function (status, xmlDoc) {
            // console.log("获取数字通道失败");
          }
        }
      );
      // TODO 模拟通道
      // 模拟通道
      WebVideoCtrl.I_GetAnalogChannelInfo(szDeviceIdentify, {
        async: false,
        mysuccess: function (xmlStr) {
          let jsonObj = that.$x2js.xml2js(xmlStr);
          // console.log("模拟通道mysuccess",xmlStr);
          // let list = jsonObj.VideoInputChannelList;
          // for (let x = 0; x < list.length; x++) {
          //   that.hkvInfo.channels.push(list[x].VideoInputChannel.id);
          // }
          var id = jsonObj.VideoInputChannelList.VideoInputChannel.id;
          that.hkvInfo.channels.push(id);
        },
        success: function (xmlStr) {
          // console.log("模拟通道success",xmlStr);
        },
        error: function (status, xmlDoc) {
          // console.log("模拟通道error",xmlDoc);
        }
      });
      // TODO 零通道
    },
    mouseDownPTZControl: function (iPTZIndex) {
      let oWndInfo = WebVideoCtrl.I_GetWindowStatus(this.mySelectWnd);
      if (oWndInfo !== null) {
        if (iPTZIndex === 9 && this.g_bPTZAuto) {
          // iPTZSpeed = 0;
        } else {
          this.g_bPTZAuto = false;
        }

        WebVideoCtrl.I_PTZControl(iPTZIndex, false, {
          iPTZSpeed: 4,
          mysuccess: function (xmlStr) {
            // console.log("I_PTZControl", xmlStr);
            if (iPTZIndex === 9 && this.g_bPTZAuto) {
              // console.log(oWndInfo.szDeviceIdentify + " 停止云台成功！mouseDown");
            } else {
              // console.log(oWndInfo.szDeviceIdentify + " 开启云台成功！mouseDown");
            }
            if (iPTZIndex === 9) {
              this.g_bPTZAuto = !this.g_bPTZAuto;
            }
          },
          error: function (status, xmlDoc) {
            // console.log(oWndInfo.szDeviceIdentify + " 开启云台失败！mouseDown", status, xmlDoc);
          }
        });
      }
    },
    mouseUpPTZControl: function () {
      let oWndInfo = WebVideoCtrl.I_GetWindowStatus(this.mySelectWnd);
      if (oWndInfo !== null) {
        WebVideoCtrl.I_PTZControl(1, true, {
          mysuccess: function (xmlStr) {
            // console.log(oWndInfo.szDeviceIdentify + " 停止云台成功！mouseUp", xmlStr)
          },
          error: function (status, xmlDoc) {
            // console.log(oWndInfo.szDeviceIdentify + " 停止云台失败！mouseUp", status, xmlDoc);
          }
        });
      }
    },
    // 视频监控 -->

  }

}
</script>
<style rel="stylesheet/scss" lang="scss">
  .active{
    color: red;
  }
  .el-dialog:not(.is-fullscreen) {
    margin-top:0vh !important;
  }
</style>
<style scoped>
  .plugin {
    width: 800px;
    height: 600px;
  }

  .my-tag {
    margin-left: 3px;
  }

  .my-group-btn {
    margin-top: 5px;
  }

</style>
<style scoped lang="scss">
  ::v-deep{
    .el-scrollbar__wrap {
      overflow-x: hidden;
    }
  }
</style>
